const {
  GoodModel
} = require('../model/good')

// 商品添加 

function handleAdd(req, res) {
  // 找有没有相同名称的数据  
  // 没有再保存
  // console.log('>>>>>>>',req.body)
  new GoodModel(req.body).save().then(result => {
    console.log(result)
    if (result) {
      res.send({
        code: 1,
        message: '保存成功'
      })
    }
  })
  // res.send({code:1,message:"成功"})
}

//商品获取
function handleList(req, res) {
  const {
    search,
    page,
    pagesize
  } = req.query

  GoodModel.find().then(result => {
    let arr = result.filter(it => it.goodname.includes(search))
    let obj = {
      code: 1,
      message: '列表请求成功',
      list: arr.slice((page - 1) * pagesize, page * pagesize),
    }
    res.send(obj)
  })
}

//价格排序
function handlePrice(req, res) {
  const {
    sortType,
    sortMethod,
    search,
    page,
    pagesize
  } = req.query

  GoodModel.find().then(result => {
    let arr = [];
    result.forEach((it) => {
      arr.push(it.price)
    });
    //升
    if (sortType == 'price' && sortMethod == 'ASC') {
      arr.sort(function (a, b) {
        return a - b
      })
      let arr1 = []
      arr.forEach((it, _) => {
        result.forEach((item, index) => {
          if (it == item.price) {
            if (arr1.indexOf(item) == -1) {
              arr1.push(item)
            }
          }
        })
      })
      let obj = {
        code: 1,
        message: '成功升序',
        list: arr1.slice((page - 1) * pagesize, page * pagesize),
      }
      res.send(obj)
    }
    //降
    if (sortType == 'price' && sortMethod == 'DESC') {
      arr.sort(function (a, b) {
        return b - a
      })
      let arr1 = []
      arr.forEach((it, _) => {
        result.forEach((item, index) => {
          if (it == item.price) {
            if (arr1.indexOf(item) == -1) {
              arr1.push(item)
            }
          }
        })
      })
      let obj = {
        code: 1,
        message: '成功降序',
        list: arr1.slice((page - 1) * pagesize, page * pagesize),
      }
      res.send(obj)
    }


  })
}


module.exports = {
  handleAdd,
  handleList,
  handlePrice
}